<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import TnForm from '@tuniao/tnui-vue3-uniapp/components/form/src/form.vue'
import TnFormItem from '@tuniao/tnui-vue3-uniapp/components/form/src/form-item.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnImageUpload from '@tuniao/tnui-vue3-uniapp/components/image-upload/src/image-upload.vue'
import TnCheckbox from '@tuniao/tnui-vue3-uniapp/components/checkbox/src/checkbox.vue'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import TnRadio from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio.vue'
import TnRadioGroup from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio-group.vue'
import TnListItem from '@tuniao/tnui-vue3-uniapp/components/list/src/list-item.vue'
import TnTag from '@tuniao/tnui-vue3-uniapp/components/tag/src/tag.vue'
import type {
  FormRules,
  ImageUploadCustomCallbackFunction,
  TnFormInstance,
} from '@tuniao/tnui-vue3-uniapp'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import PageContainer from '@/components/page-container/index'
import circles from '@/api/circles.js'
import circlesPost from '@/api/circlesPost.js'
import user from '@/api/user.js'
import {
  CHANNEL,
  FILE_URL,
  MP_API_URL,
  USER_INFO,
  USER_TOKEN,
} from '@/api/config'

// 导航栏的高度
const navbarHeight = ref(0)
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}

const formRef = ref<TnFormInstance>()
const state = reactive({
  loading: false,
  disabled: true,
  userToken: '',
  formData: {
    circles_id: 0,
    circles_zone_id: 0,
    topics_name: [],
    content: '',
    location: '',
    poiaddress: '',
    longitude: '',
    latitude: '',
    sync_homepage: 0,
    attachment_type: 'none', // 附件类型:none=无附件,image=图片,video=视频,voice=语音,link=链接
    attachment: '',
    scope_name: '公开',
    scope: 'all_see',
    channel: '',
  },
  fullImageList: [],
  imageList: [],
  videoUrl: '',
  voiceUrl: '',
  linkUrl: '',
  circlesName: '请选择圈子与分区',
  topicName: '',
  previousValue: '', // 上一个输入的内容值
  showAuthNamePopup: false,
  showLinkPopup: false,
  showTopicPopup: false,
  showCirclesPopup: false,
  showSoundRecordPopup: false,
  circlesList: [],
  currentTagIndex: -1,
  tagsData: [],
  circlesTopicList: [],
  userInfo: {},
})

const changeSyncHomepage = () => {
  if (!state.userInfo.is_vip || state.userInfo.is_vip == 0) {
    uni.showToast({
      title: '非会员不可同步！',
      duration: 3000,
      icon: 'none',
    })
    state.formData.sync_homepage = 0
  }
}
const userCirclesZone = () => {
  circles
    .userCirclesZone({
      plate: 'dynamic',
    })
    .then((res) => {
      if (res.code == 1) {
        console.log(res.data, 'userCirclesZone')
        state.circlesList = res.data
      }
    })
    .catch((err) => {
      console.log(err, 'userCirclesZone')
    })
}

const getCirclesPlateZone = (circlesId: number, circlesPlate: string) => {
  circles
    .circlesPlateZone({
      plate: circlesPlate,
      circles_id: circlesId,
    })
    .then((res) => {
      if (res.code == 1) {
        console.log(res.data, 'getCirclesPlateZone')
        state.tagsData = res.data
      }
    })
    .catch((err) => {
      console.log(err, 'getCirclesPlateZone')
    })
}

const circlesTopic = () => {
  circles
    .circlesTopic({
      page: 1,
      page_size: 20,
      recommend: 0,
      weigh: 'hot',
    })
    .then((res) => {
      if (res.code == 1) {
        console.log(res.data, 'circlesTopic')
        state.circlesTopicList = res.data
      }
    })
    .catch((err) => {
      console.log(err, 'userCirclesZone')
    })
}

// 点击分区标签
const handleTagClick = (index: number, circlesZoneId: number) => {
  state.currentTagIndex = index
  state.formData.circles_zone_id = circlesZoneId
}

const clickAuthNamePopup = () => {
  state.showAuthNamePopup = true
}
const changeAuthName = (value: any) => {
  state.formData.scope = value
  if (value == 'all_see') {
    state.formData.scope_name = '公开'
  } else if (value == 'fans_see') {
    state.formData.scope_name = '粉丝可见'
  } else if (value == 'own_see') {
    state.formData.scope_name = '仅自己可见'
  }
  state.showAuthNamePopup = false
}
const clickLinkPopup = () => {
  state.showLinkPopup = true
}
// 添加链接点击确认
const addLink = () => {
  if (state.linkUrl != '') {
    const hasHttp = /https?:\/\//.test(state.linkUrl)
    if (!hasHttp) {
      uni.showToast({
        title: '请添加正确的链接地址',
        icon: 'none',
      })
      return
    }
    state.formData.attachment = state.linkUrl
    state.formData.attachment_type = 'link'
  } else {
    state.formData.attachment_type = 'none'
  }
  state.showLinkPopup = false
  console.log(state.formData.attachment, 'linkUrl')
}

// 点击话题按钮
const clickTopicPopup = () => {
  if (state.formData.topics_name.length == 5) {
    uni.showToast({
      title: '最多可添加5个话题',
      icon: 'none',
    })
    return
  }
  circlesTopic()
  state.showTopicPopup = true
}

// 上传图片回调
const uploadCallbackHandle: ImageUploadCustomCallbackFunction = (
  data: UniApp.UploadFileSuccessCallbackResult
) => {
  const resData = JSON.parse(data.data)
  console.log(resData, 'images')
  if (resData.code == 1) {
    state.formData.attachment_type = 'image'
    state.imageList.push(resData.data.file.url)
    state.formData.attachment = state.imageList.join(',')
    console.log(state.formData.attachment, 'images2')
    return FILE_URL + resData.data.file.url
  }
}

const changeImageList = (images: any) => {
  console.log('changeImage', images)
  if (images.length == 0) {
    state.formData.attachment_type = 'none'
    state.formData.attachment = ''
  }
}
const clickImageIcon = () => {
  state.formData.attachment_type = 'image'
}

// 视频选择
const videoChooseHandle = () => {
  uni.chooseVideo({
    success: (res) => {
      console.log(res, 'videoChooseHandle')
      uni.uploadFile({
        url: `${MP_API_URL}/system.System/upload`,
        filePath: res.tempFilePath,
        name: 'file',
        header: {
          Authorization: uni.getStorageSync(USER_TOKEN),
        },
        success: (uploadFileRes) => {
          console.log(uploadFileRes, 'uploadFileRes')
          if (uploadFileRes.statusCode == 200) {
            const resData = JSON.parse(uploadFileRes.data)
            if (resData.code == 1) {
              state.formData.attachment = resData.data.file.url
              state.videoUrl = FILE_URL + resData.data.file.url
              state.formData.attachment_type = 'video'
            } else {
              uni.showToast({
                title: resData.msg,
                icon: 'error',
              })
              state.formData.attachment_type = 'none'
            }
          }
        },
      })
    },
  })
}
// 重新选择视频
const reChooseVideo = () => {
  state.formData.attachment_type = 'none'
  state.formData.attachment = ''
}

// 打开地图选择位置
const clickChooseLocation = () => {
  uni.chooseLocation({
    success(res) {
      state.formData.location = res.name
      state.formData.poiaddress = res.address
      state.formData.longitude = res.longitude
      state.formData.latitude = res.latitude
    },
  })
}

const contentChange = (value: string) => {
  if (value.length > 5) {
    state.disabled = false
  } else {
    state.disabled = true
  }
}

// 点击话题名称
const clickTopicName = (selectTopicName: string) => {
  state.showTopicPopup = false
  // state.formData.content += `#${selectTopicName}# `
  if (!state.formData.topics_name.includes(selectTopicName)) {
    // 如果不存在，则添加到数组中
    state.formData.topics_name.push(selectTopicName)
  }
  state.topicName = ''
}

const clickCircles = () => {
  state.showCirclesPopup = true
  userCirclesZone()
}

const clickSelectCircles = (
  circlesId: number,
  circlesName: string,
  circlesZone: any
) => {
  state.currentTagIndex = -1
  state.circlesName = circlesName
  state.formData.circles_id = circlesId
  state.tagsData = circlesZone
  state.showCirclesPopup = false
}

// 显示录音弹窗
const clickSoundRecordPopup = () => {
  state.showSoundRecordPopup = true
}

// 结束录音
const endSoundRecord = (event: any) => {
  console.log(event, 'event')
  if (event.tempFilePath) {
    uni.uploadFile({
      url: `${MP_API_URL}/system.System/upload`,
      filePath: event.tempFilePath,
      name: 'file',
      header: {
        Authorization: uni.getStorageSync(USER_TOKEN),
      },
      success: (uploadFileRes) => {
        console.log(uploadFileRes, 'uploadFileRes-endSoundRecord')
        if (uploadFileRes.statusCode == 200) {
          const resData = JSON.parse(uploadFileRes.data)
          if (resData.code == 1) {
            state.formData.attachment = resData.data.file.url
            state.voiceUrl = FILE_URL + resData.data.file.url
            console.log(state.voiceUrl, 'voiceUrlvoiceUrlvoiceUrl')
            state.formData.attachment_type = 'voice'
            state.showSoundRecordPopup = false
          } else {
            uni.showToast({
              title: resData.msg,
              icon: 'error',
            })
            state.formData.attachment_type = 'none'
          }
        }
      },
    })
  }
}

// 规则
const formRules: FormRules = {
  content: [
    { required: true, message: '请输入内容', trigger: ['change', 'blur'] },
    {
      min: 5,
      max: 1000,
      message: '长度在 5 到 1000 个字符',
      trigger: 'blur',
    },
  ],
}
const submitForm = () => {
  state.loading = true
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      circlesPost
        .publishDynamic(state.formData)
        .then((res) => {
          console.log(res, 'publishDynamic')
          state.loading = false
          if (res.code == 1) {
            state.disabled = true
            uni.showToast({
              title: res.msg,
            })
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              })
            }, 2000)

            updateUserLevel()
          } else {
            state.loading = false
            uni.showToast({
              title: res.msg,
              icon: 'none',
            })
          }
        })
        .catch((err) => {
          console.log(err, 'publishDynamic')
        })
    } else {
      uni.showToast({
        title: '表单校验失败',
        icon: 'none',
      })
    }
  })
}

const updateUserLevel = () => {
  user
    .updateUserLevel({
      type: 'publishDynamic',
    })
    .then((res) => {})
}
onMounted(() => {
  const userToken = uni.getStorageSync(USER_TOKEN)
  if (userToken) {
    state.userToken = userToken
  }
  state.formData.channel = uni.getStorageSync(CHANNEL)
})

onLoad((options) => {
  console.log(options, 'options')
  state.formData.circles_id = options.circlesId
  state.circlesName = options.name
  getCirclesPlateZone(options.circlesId, options.plate)

  const userInfo = uni.getStorageSync(USER_INFO)
  if (userInfo) {
    state.userInfo = userInfo
  }
})
</script>
<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      frosted
      :placeholder="false"
      :bottom-shadow="false"
      :z-index="999"
      @init-finish="navbarInitFinishHandle"
    >
      发布动态
    </TnNavbar>

    <view
      class="form-container"
      :style="{ paddingTop: `${navbarHeight + 10}px` }"
    >
      <TnForm
        ref="formRef"
        :model="state.formData"
        :rules="formRules"
        label-width="150"
        label-position="top"
      >
        <TnFormItem prop="content">
          <TnInput
            v-model="state.formData.content"
            type="textarea"
            height="300"
            :border="false"
            :focus="true"
            :maxlength="1000"
            confirm-type="done"
            placeholder="分享新鲜事～（5-1000个字）"
            @change="contentChange"
          />
          <view
            v-for="(item, index) in state.formData.topics_name"
            :key="index"
            class="topic-name"
            >#{{ item }}
            <TnIcon
              name="close"
              @click="state.formData.topics_name.splice(index, 1)"
            />
          </view>
        </TnFormItem>
        <TnFormItem
          v-if="
            state.formData.attachment_type == 'image' ||
            state.formData.attachment_type == 'none'
          "
        >
          <TnImageUpload
            v-model="state.fullImageList"
            :limit="9"
            :action="MP_API_URL + '/system.System/upload'"
            :header="{
              Authorization: state.userToken,
            }"
            :custom-upload-callback="uploadCallbackHandle"
            @change="changeImageList"
          />
        </TnFormItem>

        <TnFormItem>
          <view
            v-if="state.formData.attachment_type == 'video'"
            class="video-preview tn-gray-light_bg"
          >
            <video
              class="video-container"
              :src="state.videoUrl"
              object-fit="cover"
              :enable-progress-gesture="false"
              :show-loading="false"
              :show-play-btn="false"
              :show-fullscreen-btn="false"
              :controls="false"
              :autoplay="false"
              :enable-play-gesture="false"
              :loop="false"
            />
            <view class="remove-btn" @tap.stop="reChooseVideo">
              <view class="remove-btn--icon">
                <TnIcon name="close-fill" />
              </view>
            </view>
          </view>
        </TnFormItem>

        <TnFormItem
          v-if="state.formData.attachment_type == 'voice'"
          class="voice-preview tn-gray-light_bg"
        >
          <!-- 语音 -->
          <luch-audio
            :play.sync="true"
            :name="state.userInfo.nickname"
            author="录制完成"
            :poster="FILE_URL + state.userInfo.avatar"
            :src="FILE_URL + state.formData.attachment"
            :autoplay="false"
          />
        </TnFormItem>
        <TnFormItem
          v-if="state.formData.attachment_type == 'link'"
          class="voice-preview tn-gray-light_bg"
        >
          <!-- 链接 -->
          <uni-link
            :href="state.formData.attachment"
            :text="state.formData.attachment"
            color="#007BFF"
            copy-tips="链接已复制"
            font-size="18"
          />
        </TnFormItem>
        <view
          class="tn-border tn-gray-light_border"
          style="margin: -10rpx 0 14rpx"
        />
        <view class="circles-zone">
          <view class="zone-item">
            <view class="title">
              <TnIcon name="circle-more" />
              圈子与分区
            </view>
            <view class="content" @click="clickCircles">
              {{ state.circlesName }}
              <TnIcon name="right" />
            </view>
          </view>
          <TnTag
            v-for="(item, index) in state.tagsData"
            :key="index"
            shape="round"
            bg-color="#f8f7f8"
            :border="false"
            :border-color="
              state.currentTagIndex == index ? '#01beff' : '#ebebeb'
            "
            :text-color="state.currentTagIndex == index ? '#01beff' : '#7d7d7d'"
            :custom-style="{
              borderRadius: '6rpx',
              padding: '8rpx 10rpx',
              marginBottom: '20rpx',
              marginRight: '20rpx',
              fontSize: '24rpx',
            }"
            custom-class="zone-item tn-flex-center tn-flex-column"
            @click="handleTagClick(index, item.id)"
          >
            {{ item.name }}
          </TnTag>
        </view>
        <TnFormItem>
          <TnCheckbox
            v-model="state.formData.sync_homepage"
            checked-shape="circle"
            :custom-style="{
              padding: '30rpx 20rpx',
              backgroundColor: '#f8f7f8',
              borderRadius: '50rpx',
              height: '30rpx',
              width: '220rpx',
              overflow: 'hidden',
              fontSize: '25rpx',
              marginTop: '30rpx',
            }"
            @change="changeSyncHomepage"
          >
            同步到首页
          </TnCheckbox>
        </TnFormItem>
      </TnForm>
    </view>

    <!-- 底部悬浮按钮 -->
    <view class="tn-footerfixed">
      <view class="tags">
        <view class="left-tag">
          <TnButton
            plain
            shape="round"
            border-color="tn-grey-disabled"
            :custom-style="{
              padding: '5rpx 15rpx 5rpx 10rpx',
            }"
            @click="clickChooseLocation"
          >
            <TnIcon name="location-fill" size="35" color="tn-blue" />
            <view
              v-if="state.formData.location == ''"
              class="location-name tn-text-ellipsis-1"
              >添加地点</view
            >
            <view v-else class="location-name tn-text-ellipsis-1">{{
              state.formData.location
            }}</view>
          </TnButton>
        </view>
        <view class="right-tag tn-flex-start-end">
          <TnButton
            plain
            shape="round"
            border-color="tn-grey"
            :custom-style="{
              padding: '8rpx 15rpx',
            }"
            @click="clickAuthNamePopup"
          >
            <TnIcon v-if="state.formData.scope == 'all_see'" name="unlock" />
            <TnIcon
              v-else-if="state.formData.scope == 'fans_see'"
              name="my-love"
            />
            <TnIcon v-else-if="state.formData.scope == 'own_see'" name="lock" />
            <view class="auth-name">{{ state.formData.scope_name }}</view>
          </TnButton>
        </view>
      </view>
      <view class="menu">
        <view class="left-icon">
          <TnIcon
            v-if="
              state.formData.attachment_type == 'image' ||
              state.formData.attachment_type == 'none'
            "
            name="image"
            size="50"
            color="#e6e6e6"
          />
          <TnIcon v-else name="image" size="50" @click="clickImageIcon" />
        </view>
        <view class="left-icon">
          <TnIcon
            v-if="
              state.formData.attachment_type == 'video' ||
              state.formData.attachment_type == 'none'
            "
            name="live-stream"
            size="55"
            @click="videoChooseHandle"
          />
          <TnIcon v-else name="live-stream" color="#e6e6e6" size="55" />
        </view>
        <view class="left-icon">
          <TnIcon
            v-if="
              state.formData.attachment_type == 'voice' ||
              state.formData.attachment_type == 'none'
            "
            name="voice"
            size="50"
            @click="clickSoundRecordPopup"
          />
          <TnIcon v-else name="voice" color="#e6e6e6" size="50" />
        </view>
        <view class="left-icon">
          <TnIcon
            v-if="
              state.formData.attachment_type == 'link' ||
              state.formData.attachment_type == 'none'
            "
            name="link"
            size="50"
            @click="clickLinkPopup"
          />
          <TnIcon v-else name="link" color="#e6e6e6" size="50" />
        </view>
        <view class="left-icon">
          <TnIcon name="topic" size="50" @click="clickTopicPopup" />
        </view>
        <view class="right-button tn-flex-start-end">
          <TnButton
            type="primary"
            shape="round"
            size="xl"
            font-size="30"
            :bold="true"
            :loading="state.loading"
            :disabled="state.disabled"
            @click="submitForm"
            >发 布</TnButton
          >
        </view>
      </view>
    </view>

    <!-- 公开、私密权限 -->
    <TnPopup v-model="state.showAuthNamePopup" width="80%" height="250">
      <view class="tn-p tn-text-center tn-text-bold"> 选择发布范围 </view>
      <view class="tn-p">
        <TnRadioGroup v-model="state.formData.scope" @change="changeAuthName">
          <view class="">
            <TnRadio label="all_see">公开</TnRadio>
          </view>
          <view class="tn-mr-xs tn-ml-xs">
            <TnRadio label="fans_see">粉丝可见</TnRadio>
          </view>
          <view class="">
            <TnRadio label="own_see">仅自己可见</TnRadio>
          </view>
        </TnRadioGroup>
      </view>
    </TnPopup>

    <!-- 链接上传 -->
    <TnPopup
      v-model="state.showLinkPopup"
      :overlay-closeable="false"
      :close-btn="true"
      width="80%"
      height="270"
    >
      <view class="tn-p tn-text-center tn-text-lg"> 添加链接 </view>
      <view class="tn-pl tn-pr">
        <TnInput
          v-model="state.linkUrl"
          :underline="true"
          placeholder="请输入带有http(s)的链接"
        />
      </view>
      <view class="tn-pt-sm">
        <TnButton text width="100%" size="lg" @click="addLink">确认</TnButton>
      </view>
    </TnPopup>

    <TnPopup
      v-model="state.showSoundRecordPopup"
      :close-btn="true"
      open-direction="bottom"
      width="100%"
      height="30%"
      bg-color="#f7f7f7"
    >
      <view
        style="
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          position: fixed;
          bottom: 3vh;
        "
      >
        <all-speech
          :record-options="{
            format: 'mp3',
          }"
          :popup-fix-bottom="100"
          btn-hover-bgcolor="#b3ecff"
          @end-record="endSoundRecord"
        />
      </view>
    </TnPopup>

    <!-- 添加话题 -->
    <TnPopup
      v-model="state.showTopicPopup"
      :close-btn="true"
      open-direction="bottom"
      width="100%"
      height="90%"
    >
      <view class="tn-p tn-text-center tn-text-lg">
        <TnInput
          v-model="state.topicName"
          :border="false"
          placeholder="请输入想要添加的话题"
        >
          <template #prefix>
            <TnIcon name="topic" size="xl" />
          </template>
        </TnInput>
        <view class="tn-border tn-gray-light_border" />
      </view>
      <view class="tn-pt-xs">
        <view v-if="state.topicName != ''" class="topic-list-container">
          <TnListItem font-size="30" @click="clickTopicName(state.topicName)"
            ># {{ state.topicName }}
          </TnListItem>
        </view>
        <view v-else class="topic-list-container">
          <view class="tn-pl tn-pr tn-text recommend-title">推荐话题</view>
          <TnListItem
            v-for="(item, index) in state.circlesTopicList"
            :key="index"
            font-size="30"
            @click="clickTopicName(item.name)"
          >
            # {{ item.name }}
          </TnListItem>
        </view>
      </view>
    </TnPopup>

    <!-- 选择圈子 只能选择已关注的圈子 -->
    <TnPopup
      v-model="state.showCirclesPopup"
      :close-btn="true"
      open-direction="bottom"
      width="100%"
      height="90%"
    >
      <view class="tn-text-center tn-mt tn-text-xl"> 我关注的圈子 </view>
      <view class="circles">
        <view class="circles-list">
          <view
            v-for="(item, index) in state.circlesList"
            :key="index"
            class="list-item tn-shadow"
          >
            <view
              class="list-info"
              @click="clickSelectCircles(item.id, item.name, item.circlesZone)"
            >
              <view class="image">
                <image
                  class="tn-image"
                  :src="FILE_URL + item.image"
                  mode="aspectFill"
                />
              </view>
              <view class="title-desc">
                <view class="title tn-text-ellipsis-1">{{ item.name }}</view>
                <view class="item-desc tn-text-ellipsis-1">{{
                  item.introduce
                }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </TnPopup>
  </PageContainer>
</template>

<style lang="scss" scoped>
@use '../styles/publish/dynamic.scss';
</style>
